package com.jxc.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.jxc.dao.CommonUtilDao;
import com.jxc.entity.SessionEntity;
import com.jxc.entity.TbEmployee;
import com.jxc.dao.UsersBiz;
import com.jxc.utils.UtilDate;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.jxc.utils.CipherUtil;

public class LoginAction extends ActionSupport {

	private Log log = LogFactory.getLog(getClass());
	@Resource private UsersBiz usersBiz;
	@Resource private CommonUtilDao commonUtilDao;
	private String name;
	private String password;
	private String randCode;
	private boolean success = false;
	private String message;
	private TbEmployee tbEmployee;
	private List list = new ArrayList();

	public void login() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		ActionContext ctx = ActionContext.getContext();
		HttpServletResponse response = (HttpServletResponse) ctx
				.get(ServletActionContext.HTTP_RESPONSE);
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/json;charset=utf-8");
		String rand = (String) request.getSession().getAttribute("rand");
		if (rand == null || !randCode.equalsIgnoreCase(rand)) {
			//this.success = false;
			//this.message = "验证码错误";
			//return "success";
			try {
				response.getWriter().print("{success:'-1'}");//验证码错误
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		else
		{
			
			List<Object[]> list=usersBiz.login(name.trim(), new CipherUtil().generatePassword(password.trim()));
			Object[] obj=null;
			if(list==null){
			
				//this.message = "用户名或密码错误";
				//this.success = false;
				//return "success";
				try {
					response.getWriter().print("{success:'0'}");//用户名或密码错误
					
				} catch (IOException e) {
					e.printStackTrace();
				}							
			}else {
				
				obj=list.get(0);
				tbEmployee =(TbEmployee) obj[0] ;
				if(tbEmployee.getFlag()==0){
					response.getWriter().print("{success:'-2'}");//用户名被停用
					
				}else{
					//this.success = true;
					ServletActionContext.getRequest().getSession().setAttribute("id",
							tbEmployee.getId());
					HttpSession session = ServletActionContext.getRequest()
					.getSession();
					SessionEntity sessionEntity = new SessionEntity();
					sessionEntity.setCompanyid(tbEmployee.getTbCompany().getId());
					sessionEntity.setEmployeeID(tbEmployee.getId());
					sessionEntity.setUserName(tbEmployee.getUserName());
					sessionEntity.setCompanyName(tbEmployee.getTbCompany().getName());
					sessionEntity.setName(tbEmployee.getName());
					sessionEntity.setZome(tbEmployee.getTbCompany().getTbCity().getCityName()+tbEmployee.getTbCompany().getTbDistrict().getDistrictName());
					sessionEntity.setNumber(tbEmployee.getNumber());

					//sessionEntity.setRoleId(Integer.valueOf(obj[1].toString()));
					List<Integer> roleIdList = new ArrayList<Integer>();
					List roleNameList=new ArrayList();
				    for(Object[] object : list){
				    	roleNameList.add(object[2].toString());
				    	roleIdList.add(Integer.valueOf(object[1].toString()));
					}
				    sessionEntity.setRoleId(roleIdList);
				    sessionEntity.setRoleNameList(roleNameList);
					session.setAttribute("sessionEntity", sessionEntity);
					
					try {
						response.getWriter().print("{success:'1'}");//登陆成功
					} catch (IOException e) {
						e.printStackTrace();
					}
				}

			}
		}
		
	}
	/**
     * 获得客户端真是ip
     */
    public String getIpAddr(HttpServletRequest request) {    
        String ip = request.getHeader("x-forwarded-for");    
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
            ip = request.getHeader("Proxy-Client-IP");    
        }    
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
            ip = request.getHeader("WL-Proxy-Client-IP");    
        }    
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
            ip = request.getRemoteAddr(); 
        } 
        return ip;
    }
	/**
	 * 登出操作
	 * 
	 * @return
	 */
	public String logout() {
		Integer id = (Integer) ServletActionContext.getRequest().getSession()
				.getAttribute("id");
		if (id != null) {
			tbEmployee = this.usersBiz.login(id);
			log.info("用户" + tbEmployee.getUserName() + "在"
					+ UtilDate.timeToString(new Date()) + "退出了系统");
		}
		ServletActionContext.getRequest().getSession().removeAttribute("id");
		ServletActionContext.getRequest().getSession().invalidate();
		return "logout";
	}

	/**
	 * 登录后
	 * 
	 * @param id
	 */
/*	private void loginIndex() {
		ActionContext ctx = ActionContext.getContext();
		HttpServletResponse response = (HttpServletResponse) ctx
				.get(ServletActionContext.HTTP_RESPONSE);
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/json;charset=utf-8");
		Integer id = (Integer) ServletActionContext.getRequest().getSession()
				.getAttribute("id");
		String HQL = "select  tbr.role_id, tbr.name ,tbm.menu_name,tbm.parent_id,tbm.menu_param,tbm.is_menu,tbp.access_key_name,tbp.access_value , tbem.company_id , tbem.id , tbem.userName, tbem.dept  from   tb_role as tbr,tb_permission_role as tbp,tb_employee_role as tbe ,tb_employee  as tbem,tb_menu as tbm  where  tbr.role_id =tbp.role_id and tbm.menu_id=tbp.menu_id and  tbe.user_id=tbem.id and tbem.id='"
				+ id
				+ "'   group by  tbr.role_competence, tbr.name ,tbm.menu_name,tbm.parent_id,tbm.menu_param,tbm.is_menu,tbp.access_key_name,tbp.access_value , tbem.company_id , tbem.id , tbem.userName, tbem.dept";
		List list1 = this.commonUtilDao.QueryNativeList(HQL);
		Object[] obj = null;
		String json = "{";
		for (int i = 0; i < list1.size(); i++) {
			obj = (Object[]) list1.get(i);
			BasicBean bb = new BasicBean();
			String ismenu = "";
			String menuname = "";
			String menuparam = "";
			String parentid = "";
			if (obj[0] != null) {
				bb.setRoleID(Integer.parseInt(obj[0].toString()));
			}
			if (obj[1] != null) {
				bb.setRoleName(obj[1].toString());
			}
			if (obj[2] != null) {
				menuname = obj[2].toString();
				bb.setMenuname(obj[2].toString());
			}
			if (obj[3] != null) {
				parentid = obj[3].toString();
				bb.setParentid(Integer.parseInt(obj[3].toString()));
			}
			if (obj[4] != null) {
				menuparam = obj[4].toString();
				bb.setMenuparam(obj[4].toString());
			}
			if (obj[5] != null) {
				ismenu = obj[5].toString();
				bb.setIsmenu(Integer.parseInt(obj[5].toString()));
			}
			if (obj[6] != null) {
				bb.setAccesskeyname(obj[6].toString());
			}
			if (obj[7] != null) {
				bb.setAccessvalue(obj[7].toString());
			}
			if (obj[8] != null) {
				bb.setCompanyid(Integer.parseInt(obj[8].toString()));
			}
			if (obj[9] != null) {
				bb.setUserID(Integer.parseInt(obj[9].toString()));
			}
			if (obj[10] != null) {
				bb.setUserName(obj[10].toString());
			}
			if (obj[11] != null) {
				bb.setDept(obj[11].toString());
			}
			// for (int i = 0; i < list1.size(); i++) {
			json += "{ismenu:'" + ismenu + "',menuname'" + menuname
					+ "',menuparam'" + menuparam + "',parentid'" + parentid
					+ "'}";
			if (i != list1.size() - 1) {
				json += ",";
			}
		}
		json += "}";
		try {
			response.getWriter().print(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}*/

	public void menulist() {
		ActionContext ctx = ActionContext.getContext();
		HttpServletResponse response = (HttpServletResponse) ctx
				.get(ServletActionContext.HTTP_RESPONSE);
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/json;charset=utf-8");
		Integer id = (Integer) ServletActionContext.getRequest().getSession()
				.getAttribute("id");
		String HQL = "select  tbr.role_id, tbr.name ,tbm.menu_name,tbm.parent_id,tbm.menu_param,tbm.is_menu,tbp.access_key_name,tbp.access_value , tbem.company_id , tbem.id , tbem.userName, tbem.dept  from   tb_role as tbr,tb_permission_role as tbp,tb_employee_role as tbe ,tb_employee  as tbem,tb_menu as tbm  where  tbr.role_id =tbp.role_id and tbm.menu_id=tbp.menu_id and  tbe.user_id=tbem.id and tbem.id='"
				+ id
				+ "'   group by  tbr.role_competence, tbr.name ,tbm.menu_name,tbm.parent_id,tbm.menu_param,tbm.is_menu,tbp.access_key_name,tbp.access_value , tbem.company_id , tbem.id , tbem.userName, tbem.dept";
		List list1 = this.commonUtilDao.QueryNativeList(HQL);
		Object[] obj = null;
		String ismenu = "";
		String menuname = "";
		String menuparam = "";
		String parentid = "";
		int a[] = { 0, 1, 2, 3, 4, 5 };
		String json = "[";
		for (int i = 0; i < list1.size(); i++) {
			obj = (Object[]) list1.get(i);
			int parentids = Integer.valueOf(obj[3].toString());
			 json = "[";
			for (int j = 0; j < a.length; j++) {
				if (a[j] == parentids) {
					if (obj[2] != null) {
						menuname = obj[2].toString();
					}
					if (obj[3] != null) {
						parentid = obj[3].toString();
					}
					if (obj[4] != null) {
						menuparam = obj[4].toString();
					}
					if (obj[5] != null) {
						ismenu = obj[5].toString();
					}
					json += "{ismenu:'" + ismenu + "',menuname'" + menuname
							+ "',menuparam'" + menuparam + "',parentid'"
							+ parentid + "'}";
					if (i != a.length - 1) {
						json += ",";
					}
				}
				json += "]";
			}
			if (i != list1.size() - 1) {
				json += ",";
			}
		}
		json = "]";
		try {
			response.getWriter().print(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getRandCode() {
		return randCode;
	}

	public void setRandCode(String randCode) {
		this.randCode = randCode;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

}

